﻿/// <reference path="../sage/sage.util.js" />
/// <reference path="./painters/fourkill.painter.ZZ.singletons.js" />
/// <reference path="./objects/fourkill.testdude.serverobject.js" />
/// <reference path="../sage/sage.input.ZZ.singletons.js" />

var FourKillGameInputHandlers = {
    Tap: FourKillGameView_Tap.newInstance(),
    ObjectLocation: FourKillGameView_ObjectLocation.newInstance()
};

var FourKillGameView = Base.extend({
    initialize: function initialize(host) {
        //this.bgMusic = null;
        this.host = host;
        this.paintingContext = null;
        this.painters = [];
        this.objects = [];
        this.inputs = [];
        this.paintInterval = null;
        this.frameRate = 100;
        this.viewId = "fourkill";
        this.isActive = false;
        this.volume = 0.0;
    },
    setup: function setup() {
        /*this.bgMusic = $("#bgMusic").get(0);
        if (this.bgMusic != null) {
            this.bgMusic.loop = "loop";
            this.bgMusic.play(0);
            this.bgMusic.volume = this.volume;
        }*/
        var $backCanvas = $('<canvas/>', { 'class': 'radHuh', 'id': 'backCanvas' })
           .attr("width", $(window).width())
           .attr("height", $(window).height())
           .offset({ top: 0, left: 0 })
           .css("position", "absolute")
           .css("zIndex", "0");

        var $foreCanvas = $('<canvas/>', { 'class': 'radHuh', 'id': 'foreCanvas' })
           .attr("width", $(window).width())
           .attr("height", $(window).height())
           .offset({ top: 0, left: 0 })
           .css("position", "absolute")
           .css("zIndex", "1");

        $(document.body).append($backCanvas);
        $(document.body).append($foreCanvas);

        var playerData = this.host.svc.login("Jimmy", "password");
        var pp3d = util.toECEF(playerData.latitude, playerData.longitude);
        
        this.paintingContext = PaintingContext.newInstance();
        this.paintingContext.backLayer = $backCanvas.get(0).getContext("2d");
        this.paintingContext.frontLayer = $foreCanvas.get(0).getContext("2d");
        this.paintingContext.viewPort = ViewPort.newInstance(6, util._90, util._45);
        this.paintingContext.camera = Placement.newInstance();
        this.paintingContext.camera.z = 0;
        this.paintingContext.camera.x = pp3d.x;
        this.paintingContext.camera.y = pp3d.y;
        this.paintingContext.camera.w = 1;
        this.paintingContext.camera.h = 2;
        this.paintingContext.camera.setBearing(playerData.bearing);

        this.painters.push(Painters.Sky2);
        this.painters.push(Painters.Ground);
        this.objects.push(MistObject.newInstance(1000, 0.2));

        if (GlobalInputHandlers.Tap.isAvailable()) {
            GlobalInputHandlers.Tap.setup();
        }
        this.inputs.push(FourKillGameInputHandlers.Tap);

        if (GlobalInputHandlers.ObjectLocation.isAvailable()) {
            GlobalInputHandlers.ObjectLocation.setup();
        }
        this.inputs.push(FourKillGameInputHandlers.ObjectLocation);

        /***********************************************************/
        var pc = this.paintingContext;
        /*
        //Trees
        for (var j = 0; j < 1000; j++) {
            var s = util.random(5, 15);
            var tree = TreeObject.newInstance();
            tree.w = s;
            tree.h = s;
            tree.z = 0;
            tree.x = util.random(pc.camera.x - 1600, pc.camera.x + 1600);
            tree.y = util.random(pc.camera.y - 1600, pc.camera.y + 1600);
            tree.setBearing(util.radians(util.random(180)));
            tree.update();
            this.objects.push(tree);
        }

        //Clouds
        for (var i = 0; i < 25; i++) {
            var cloud = CloudObject.newInstance();
            cloud.h = util.random(50, 300);
            cloud.w = cloud.h * 2;
            cloud.x = util.random(pc.camera.x - 1800, pc.camera.x + 1800);
            cloud.y = util.random(pc.camera.y - 1800, pc.camera.y + 1800);
            cloud.z = util.random(400, 600);
            cloud.speed = Math.random() * .04;
            cloud.update();
            this.objects.push(cloud);
        }

        //Birds
        for (var j = 0; j < 30; j++) {
            var bird = FlyingBirdObject.newInstance();
            bird.bearing = util.radians(util.random(0, 359));
            bird.h = util.random(2, 4);
            bird.w = bird.h;
            bird.x = util.random(pc.camera.x - 500, pc.camera.x + 500);
            bird.y = util.random(pc.camera.y - 500, pc.camera.y + 500);
            bird.color = "rgb(" + util.random(0, 255) + ", " + util.random(0, 255) + ", " + util.random(0, 255) + ")";
            bird.update();
            this.objects.push(bird);
        }
        
        var hitler = ServerObject.newInstance(AdvancedSprites.Hitler);
        hitler.objectId = 1;
        hitler.h = 6;
        hitler.w = 4;
        hitler.x = util.random(pc.camera.x - 200, pc.camera.x + 200);
        hitler.y = util.random(pc.camera.y - 200, pc.camera.y + 200);
        hitler.update();
        this.objects.push(hitler);

        //Test Sprites
        for (var j = 0; j < 100; j++) {
            var dude = null;
            if ((j % 4) == 0) dude = TestDudeObject.newInstance(AdvancedSprites.Hero);
            else if ((j % 3) == 0) dude = TestDudeObject.newInstance(AdvancedSprites.Spencer);
            else dude = TestDudeObject.newInstance(AdvancedSprites.Marine);

            dude.bearing = util.radians(util.random(0, 359));
            dude.h = 2;
            dude.w = 1;
            dude.x = util.random(pc.camera.x - 200, pc.camera.x + 200);
            dude.y = util.random(pc.camera.y - 200, pc.camera.y + 200);
            dude.color = "rgb(" + util.random(0, 255) + ", " + util.random(0, 255) + ", " + util.random(0, 255) + ")";
            dude.update();
            this.objects.push(dude);
        }

        //Markers 
        var staticObjects = this.host.svc.getStaticObjectsInLocation();
        for (var j = 0; j < staticObjects.length; j++) {
            var mrkrData = staticObjects[j];
            var p3d = util.toECEF(mrkrData.latitude, mrkrData.longitude);
            var marker = MapMarkerObject.newInstance(mrkrData.name + " (" + p3d.x + "," + p3d.y + ")");
            marker.w = 1;
            marker.h = 1;
            marker.z = 6;
            marker.x = p3d.x;
            marker.y = p3d.y;
            marker.color = "rgb(" + util.random(0, 255) + ", " + util.random(0, 255) + ", " + util.random(0, 255) + ")";
            marker.setBearing(mrkrData.bearing);
            marker.update();
            this.objects.push(marker);
        }
        */

        var tdo = ThreeDimensionalObject.newInstance();
        tdo.h = 20;
        tdo.w = 20;
        tdo.x = util.random(pc.camera.x - 200, pc.camera.x + 200);
        tdo.y = util.random(pc.camera.y - 200, pc.camera.y + 200);
        tdo.z = 0;
        tdo.addPolygon(
            [10, 10, 0],
            [-10, 10, 0],
            [-10, 10, 20],
            [10, 10, 20]);

        tdo.addPolygon(
			[10, 10, 0],
			[10, -10, 0],
			[10, -10, 20],
			[10, 10, 20]);

        tdo.addPolygon(
			[10, -10, 0],
			[-10, -10, 0],
			[-10, -10, 20],
			[10, -10, 20]);

        tdo.addPolygon(
			[-10, 10, 0],
			[-10, -10, 0],
			[-10, -10, 20],
			[-10, 10, 20]);

        tdo.addPolygon(
			[10, 10, 20],
			[-10, 10, 20],
			[-10, -10, 20],
			[10, -10, 20]);

        this.objects.push(tdo);


        /***********************************************************/

        for (var k = 0; k < this.inputs.length; k++) {
            if (this.inputs[k].isAvailable()) {
                this.inputs[k].enable();
            }
        }

        this.paintInterval = setInterval((function (self) { return function () { self.paint(); } })(this), this.frameRate);
        this.isActive = true;
    },
    teardown: function teardown() {
        for (var k = 0; k < this.inputs.length; k++) {
            if (this.inputs[k].enabled) {
                this.inputs[k].disable();
            }
        }
        $(this.paintingContext.backLayer.canvas).remove();
        $(this.paintingContext.frontLayer.canvas).remove();
        this.paintingContext = null;
        this.painters.length = 0;
        this.inputs.length = 0;
        this.objects.length = 0;
        if (this.paintInterval != null) {
            clearInterval(this.paintInterval);
            this.paintInterval = null;
        }
        this.isActive = false;
        //this.bgMusic.pause();
    },
    pause: function pause() {
        //this.bgMusic.pause();
        for (var k = 0; k < this.inputs.length; k++) {
            if (this.inputs[k].enabled) {
                this.inputs[k].disable();
            }
        }
        if (this.paintInterval != null) {
            clearInterval(this.paintInterval);
            this.paintInterval = null;
        }
    },
    resume: function resume() {
        //this.bgMusic.play();
        for (var k = 0; k < this.inputs.length; k++) {
            if (!this.inputs[k].enabled) {
                this.inputs[k].enable();
            }
        }
        if (this.paintInterval == null) {
            this.paintInterval = setInterval((function (self) { return function () { self.paint(); } })(this), this.frameRate);
        }
    },
    resize: function resize() {
        if (this.isActive) {
            var pc = this.paintingContext;
            pc.frontLayer.canvas.height = $(window).height();
            pc.frontLayer.canvas.width = $(window).width();
            pc.backLayer.canvas.height = $(window).height();
            pc.backLayer.canvas.width = $(window).width();
            this.paint();
        }
    },
    paint: function paint() {
        // bring music volume up
        //if (this.bgMusic.volume < .5) this.bgMusic.volume += .005;

        var pc = this.paintingContext,
            fc = this.paintingContext.frontLayer,
            bc = this.paintingContext.backLayer;

        for (var k = 0; k < this.inputs.length; k++) {
            if (this.inputs[k].enabled) {
                this.inputs[k].update(pc);
            }
        }
        fc.clearRect(0, 0, fc.canvas.width, fc.canvas.height);
        pc.viewPort.setPixelSize(fc.canvas.width, fc.canvas.height);
        pc.gameObject = null;
        
        for (var i = 0; i < this.painters.length; i++) {
            this.painters[i].paint(pc);
        }

        for (var i = 0; i < this.objects.length; i++) this.objects[i].updateLocation(pc);

        // Order painters by distance
        util.orderByDistance(this.objects);

        // Paint away!
        for (var i = 0; i < this.objects.length; i++) {
            var o = this.objects[i];
            if (ServerObject.isPrototypeOf(o)) {
                var location = FourKillGameInputHandlers.ObjectLocation.getLocation(o.objectId);
                if (location != null) o.serverLocation = location;
            }
            o.tick();
            if (o.locationRelativeToCamera != null && o.locationRelativeToCamera.visible) {
                pc.gameObject = o;
                o.getPainter().paint(pc);
            }
        }
    }
});
